package cn.imvc.core;

import java.io.IOException;
import java.io.PrintWriter;

public class Render {
	public static String text(String text) {
		HttpContext.getResponse().setContentType("text/plain;charset=UTF-8");
		PrintWriter printWriter = null;
		try {
			printWriter = HttpContext.getResponse().getWriter();
			printWriter.write(text);
			printWriter.flush();
		} catch (IOException e) {

		} finally {
			printWriter.close();
			try {
				HttpContext.getResponse().flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static String json(Object object) {

		if (object instanceof String) {
			String json = object.toString().replace('\'', '"');
			renderTextJson(json);
		} else {
			renderObjectJson(object);
		}
		return null;
	}
	private static void renderTextJson(String textJson) {
		HttpContext.getResponse().setContentType("application/json;charset=UTF-8");
		PrintWriter printWriter = null;
		try {
			printWriter = HttpContext.getResponse().getWriter();
			printWriter.write(textJson);
			printWriter.flush();
		} catch (IOException e) {

		} finally {
			printWriter.close();
			try {
				HttpContext.getResponse().flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	private static void renderObjectJson(Object object) {
		HttpContext.getResponse().setContentType("application/json;charset=UTF-8");
		net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(object);
		PrintWriter printWriter = null;
		try {
			printWriter = HttpContext.getResponse().getWriter();
			printWriter.write(jo.toString());
			printWriter.flush();
		} catch (IOException e) {

		} finally {
			printWriter.close();
			try {
				HttpContext.getResponse().flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String redirect(String url) {
		try {
			HttpContext.getResponse().sendRedirect(
					HttpContext.getContext().getAttribute("rootUrl") + url);
			HttpContext.getResponse().flushBuffer();
		} catch (IOException e) {

		}
		return null;
	}

}
